<?php
/*
*  index.php
*  Controller for po-php-fwlite  框架核心路由文件
*  Guo Jia(Anthemius, NJ.weihang@gmail.com)
*  http://code.google.com/p/po-php-fwlite
*
*  Created by Guo Jia on 2008-3-12.
*  Copyright 2008-2012 Guo Jia All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

$g_access_mode = -2;
//for difference as the cron running/api running
$g_debug_time = true;
ignore_user_abort(true);
/*  >php -q s.php 1 12345
1: table id
12345: socket id*/
$table_id = 1;
$g_server_name = 'local';

include_once 'processes/base_init.process.php';
include_once IR.'config/server/'.$g_server_name.'.config.php';
include_once IR.'functions/common/base.func.php';
include_once IR.'functions/common/db.func.php';

db_connect();
$seed = rand();
mt_srand($seed);

include_once IR."functions/common/websocket.func.php";
set_time_limit(0);
ob_implicit_flush();

$master  = WebSocket("localhost",12345);
$sockets = array($master);
$users   = array();
$debug   = false;

while(true){
  $changed = $sockets;
  socket_select($changed,$write=NULL,$except=NULL,NULL);
  foreach($changed as $socket){
    if($socket==$master){
      $client=socket_accept($master);
      if($client<0){ console("socket_accept() failed"); continue; }
      else{ connect($client); }
    }
    else{
      $bytes = @socket_recv($socket,$buffer,2048,0);
      if($bytes==0){ disconnect($socket); }
      else{
        $user = getuserbysocket($socket);
        if(!$user->handshake){ dohandshake($user,$buffer); }
        else{ process($user,$buffer); }
      }
    }
  }
}

function process($user,$msg){
	$req = unwrap($msg);
	say("< ".$req);
	$json_req = json_decode($req);
	$g_module = $json_req['m'];
	$g_action = $json_req['a'];
	if (!file_exists(IR.'/server_proc/'.$g_module.'/'.$g_action.'.php')){
		send($user->socket,json_encode(array('rstno'=>-999,'err'=>"fuck human"))); 
	} else {
		include_once(IR.'/server_proc/'.$g_module.'/'.$g_action.'.php');
		send($user->socket,json_encode($json_rst)); 
	}
}
?>